/*************************************************
* Title：TinyToolKit
* Author：Opportunity 
* Discribe：扩展场景加载的功能
 * 异步加载场景
* CreateTime：2020-04-29 16:58:26
* Version：1.0
* Modify Recoder：
*************************************************/

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;

namespace TinyToolKit
{
    public static partial class TinyUtility
    {
        public static class SceneHelper
        {
            private static bool _isLoadingScene = false;//判断是否正在加载场景中...
            
            /// <summary>
            /// 异步加载场景
            /// </summary>
            /// <param name="sceneName">需要加载的场景名字</param>
            /// <param name="loadingProgressFunc">处理加载进度的函数</param>
            /// <param name="sceneLoadedCallback">异步加载场景结束时的回调函数</param>
            public static void LoadSceneAsync(string sceneName,Action<float> loadingProgressFunc,Action sceneLoadedCallback = null)
            {
                if (_isLoadingScene || string.IsNullOrEmpty(sceneName)) return;
                
                TinyTool.Instance.StartCoroutine(LoadingSceneAsync(sceneName,loadingProgressFunc,sceneLoadedCallback));  
            }

            private static IEnumerator LoadingSceneAsync(string sceneName,Action<float> loadingProgressFunc,Action sceneLoadedCallback = null)
            {
                int displayProgress = 0;
                int toProgress = 0;
                _isLoadingScene = true;
                
                AsyncOperation op = SceneManager.LoadSceneAsync(sceneName);
                op.allowSceneActivation = false;
                while (op.progress < 0.9f) 
                {
                    toProgress = (int)(op.progress * 100);
                    while (displayProgress < toProgress)
                    {
                        displayProgress++;
                        loadingProgressFunc?.Invoke(displayProgress); 
                        yield return new WaitForEndOfFrame();
                    }
                }

                toProgress = 100;
                while (displayProgress < toProgress)
                {
                    displayProgress++;
                    loadingProgressFunc?.Invoke(displayProgress);
                    yield return new WaitForEndOfFrame(); 
                }
                op.allowSceneActivation = true;
                
                _isLoadingScene = false;
                sceneLoadedCallback?.Invoke();
            }                           
        }
    }
}

